package suanfa;

public class SingleChain<V> {
    private int size;
    private Node<V> head;
    private Node<V> tail;

    public void add(V val) {
        Node<V> node = new Node(val);
        if (null == tail) {
            head = node;
            tail = node;
        } else {
            tail.next = node;
            tail = node;
        }
        size++;
    }

    public V peek() {
        if (null == head) {
            return null;
        }
        return head.val;
    }

    public void push(V val) {
        Node<V> node = new Node<>(val);
        if (null == head) {
            head = node;
            tail = node;
        } else {
            node.next = head;
            head = node;
        }
        size++;
    }

    public V pop() {
        if (null == head) {
            return null;
        } else {
            V val = head.val;
            head = head.next;
            size--;
            return val;
        }
    }

    public int size() {
        return size;
    }

    public void printChain() {
        Node<V> node = head;
        while (null != node) {
            System.out.print(node.val + " -> ");
            node = node.next;
        }
        System.out.print("NULL");
        System.out.println("; Size:" + size());
    }

    private static class Node<V> {
        private final V val;
        private Node<V> next;

        public Node(V val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        SingleChain<Integer> chain = new SingleChain<>();
        //2、使用单链表实现队列
        System.out.print("入队操作：");
        for (int i = 0; i < 10; i++) {
            chain.add(i);
            System.out.print(i+" -> ");
        }
        System.out.println("NULL");
        //打印结果：Size:10,  0 -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8 -> 9 -> NULL,  Size:0
        //表示为先进先出，表现为队列
        System.out.print("出队结果：");
        chain.printPop();
        System.out.println();
        //1、使用单链表实现栈
        System.out.print("压栈操作：");
        for (int i = 0; i < 10; i++) {
            chain.push(i);
            System.out.print(i+" -> ");
        }
        System.out.println("NULL");
        //打印结果：Size:10,  9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0 -> NULL,  Size:0
        //表示为后进先出，表现为栈
        System.out.print("出栈结果：");
        chain.printPop();
    }

    private void printPop() {
        System.out.print("Size:" + size() + ",  ");
        V val;
        while (null != (val = pop())) {
            System.out.print(val + " -> ");
        }
        System.out.print("NULL");
        System.out.println(",  Size:" + size());
    }
}
